<?php
	if(!$_POST)
		header('Location: /errors/404.html');

	require_once('./fw/sqllib.php');
	require_once('./fw/img.php');

	//GET POST DATA
	$data = array();
	
	if($data['name'])
	$data['name']  = mysql_escape_string($_POST['name']);
	$data['title'] = mysql_escape_string($_POST['title']);
	$data['text']  = mysql_escape_string($_POST['text']);
	$data['board'] = mysql_escape_string($_POST['board']);

	//PROCESS POST DATA
	//get password
	$cap  = explode('#',$data['name']);
	$name = $cap[0];
	$cap  = $cap[1];
	if($cap != "") {
		//generate tripcode
		$cap  = strtr($cap, "&amp;", "&");
		$cap  = strtr($cap, "&#44;", ", ");
		$salt = substr($cap."H.", 1, 2);
		$salt = preg_replace("/[^\.-z]/", ".", $salt);
		$salt = strtr($salt, ":;<=>?@[\\]^_`", "ABCDEFGabcdef");
		$tripcode = substr(crypt($cap, $salt), -10);	
		
		$data['name'] = "$name!$tripcode";
	}

	//UPLOADING IMAGE
	if($_FILES['picture']['name']) {
		/////////////////////////
		//CHECKING IMAGE

		$MAX_SIZE = 5*1048576; //5 mb
		$ALLOWED_EXTENSIONS = array('jpg', 'jpeg', 'gif', 'png');
		$THUMB_SIZE = 200;
		
		$image 	   = $_FILES['picture'];
		$tmppath   = $image['tmp_name'];
		$imagename = $image['name'];
		
		//getting image extension
		$l = strrpos($imagename, '.')+1;
		$ext = strtolower(substr($imagename, $l, 4));
		//yep
		$size = filesize($image['tmp_name']);
		
		if(!in_array($ext, $ALLOWED_EXTENSIONS)) {
			//fuck you and your stupid image
		}
		if($size > $MAX_SIZE) {
			//oh you
		}
		
		////////////////////////
		//SAVING IMAGE

		//generate unique name for image
		$imagename = time();
		$imagepath = "pics/$imagename.$ext";
		$thumbpath = "pics/s/$imagename.png";
		$imagename .= ".$ext";

		//generate thumbnail
		$thumbnail = getthumb($tmppath, $ext, $THUMB_SIZE);
		
		//save thumbnail and image
		imagepng($thumbnail, $thumbpath);
		copy($tmppath, $imagepath);

		$data['pic']  = $imagename;
	}
	
	//PREPARE MYSQL DATA
	if($_POST['thread']) {
		//yep thats a thread
		$data['isop'] = 1;
	} else if($_POST['thread_id']) {
		//its a post
		$tid = mysql_escape_string($_POST['thread_id']);
		$data['thread_id'] = $tid;
		
		$db->update('posts', array('bump' => 'CURRENT_TIMESTAMP()', 'replies' => 'replies+1'), array('id' => '='.$tid));
		$db->query();
	}
	
	//SUBMIT DATA
	$db->insert('posts', $data);
	$db->query();

	echo '<meta http-equiv="refresh" content="0; url='.$_SERVER['HTTP_REFERER'].'">';
?>
